from __future__ import absolute_import, unicode_literals

import time

from celery import shared_task
from django.conf import settings

from goodsManage import models
from django.db import close_old_connections


from tools.tool import get_time_uid


@shared_task
def add(x, y):
    time.sleep(30)
    print("celery结果")
    return x + y
@shared_task
def test():
    time.sleep(30)
    return 1
    # with open(settings.BASE_DIR+'/tes.txt', 'w+', encoding='utf-8') as f:
    #     f.write('77777777\n')


@shared_task
def mul(x, y):
    print('x*y')
    return x * y

@shared_task
def rushtask(user_id, rushgoods_id):
    close_old_connections()
    rushgood = models.RushGoods.objects.filter(id=rushgoods_id).last()
    if rushgood:
        if rushgood.number > 0:
            price = rushgood.rushprice
            total = price
            uid = get_time_uid()
            models.Order.objects.create(
                    uid=uid,
                    goods_id=rushgood.goods_id,
                    price=price,
                    number=1,
                    total=total,
                    user_id=user_id,
                    isrush=1
            )
            return 1
        else:
            return 0
    return 0

@shared_task
def task_create_rushGoods():
    close_old_connections()
    create_rushGoods()

def create_rushGoods():
    """
    创建抢购的商品
    """
    goods = models.Goods.objects.filter().order_by('?')[:4]
    for good in goods:
        rushprice = good.price * 0.85
        rushprice = round(rushprice, 2)
        models.RushGoods.objects.create(
            goods=good,
            rushprice=rushprice,
            total=10,
            number=10,
        )